package com.tarena.test.rabbitmq.works;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import org.junit.Before;
import org.junit.Test;

//模拟工作争抢消息的模式
public class WorkMode {
    private Channel channel;
    @Before
    public void initChannel() throws IOException, TimeoutException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");
        Connection connection= factory.newConnection();
        channel=connection.createChannel();
    }
    //声明一个测试使用的队列
    @Test
    public void declareQueue() throws IOException {
        System.out.println("开始声明队列");
        channel.queueDeclare("work-q",true,false,false,null);
        System.out.println("队列声明完毕");
    }
    //第一个消费者监听绑定
    @Test
    public void consumer01() throws IOException {
        DeliverCallback deliverCallback= (consumerTag, message) -> {
            //测试环境中 可以打印一些数据
            System.out.println("当前消费者tag:"+consumerTag);
            //从消息中解析数据 打印
            byte[] body = message.getBody();
            String msg=new String(body);
            System.out.println("消费者接收到消息:"+msg);
        };
        CancelCallback cancelCallback= consumerTag -> {
            //TODO
        };
        channel.basicConsume("work-q",true,deliverCallback,cancelCallback);
        while(true);
    }
    @Test
    public void consumer02() throws IOException {
        DeliverCallback deliverCallback= (consumerTag, message) -> {
            //测试环境中 可以打印一些数据
            System.out.println("当前消费者tag:"+consumerTag);
            //从消息中解析数据 打印
            byte[] body = message.getBody();
            String msg=new String(body);
            System.out.println("消费者接收到消息:"+msg);
        };
        CancelCallback cancelCallback= consumerTag -> {
            //TODO
        };
        channel.basicConsume("work-q",true,deliverCallback,cancelCallback);
        while(true);
    }
    //批量发送消息
    @Test
    public void sendBatchMessage() throws IOException {
        System.out.println("生产者即将发送批量消息");
        for(int i=0;i<100;i++){
            String msg="我的第["+i+"]条消息";
            channel.basicPublish("","work-q",null,msg.getBytes());
            System.out.println("生产者正在发送:"+msg);
        }
        System.out.println("生产者发送结束");
    }
}
